require('../../im/stylesheet/demo.scss');

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import _ from 'lodash';
import { Button, Icon, Form, message, Tag, Tabs, Input, Tree, Row, Col, Checkbox,Select,Radio,Modal } from 'antd';
import { connect } from 'react-redux'
import {
  API_URL,
  PORTRAIT,
  FetchURL,
  fetchArgs,
  fetchData,
  fetchOrderSpecial,
  formItemLayout,
  fetchDatum,
  _validate,
  fetchUserImage,
  fetchPatient,
  fetchReport,
  fetchOrderRelatedData,
  orderOperator,
  createReport,
  editReport,
  openWeiyi,
  fetchAttachById
} from '../../store/actions';
import Api  from '../../im/javascript/src/api'
import {ImEntry}  from '../../im/javascript/src/im-comp'
const TabPane = Tabs.TabPane,
  TreeNode = Tree.TreeNode,
  CheckboxGroup = Checkbox.Group,
  FormItem = Form.Item,
  Option = Select.Option,
  RadioGroup = Radio.Group,
  RadioButton = Radio.Button,
  confirm = Modal.confirm;

require('../../../css/specialist.css');
class WriteReport extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            cur:this.props.orderId,
            orderData: this.props.orderData
        };
        this.beforeCompletion = this.beforeCompletion.bind(this)
    }

    beforeCompletion(id,type){
        const _this = this;
        confirm({
            title:'您确定要完成这个订单？',
            content:`完成订单后将不能再次编辑报告内容!`,
            onOk(){
                _this.orderCompletion(id,function(){
                    _this.props.orderChange(id,type,3)
                })
            },
            onCancel(){
            }
        })
    }
    orderCompletion(id,cb){
        this.props.dispatch(orderOperator(id,'completion',function(res){
            message.success('订单完成');
            if(typeof cb == 'function'){cb()}
        }))
    }
    endOrder(e){
        const _this = this,
          report = _this.state.orderData.report,
          id = _this.state.cur,
          type = _this.state.orderData.type;
        _validate(e,_this,function(data){
            let submit = Object.assign({},data,{order_id:id,template_id:0});
            if(report){
                submit = Object.assign({},data,{
                    id:report.id
                });
                _this.props.dispatch(editReport(submit))
            }else{
                _this.props.dispatch(createReport(submit))
            }
            _this.beforeCompletion(id,type)

        })
    }
    saveReport(){
        const _this = this,
          data = _this.props.form.getFieldsValue(),
          report = _this.state.orderData.report;
        let count= 0,
          submit = {};
        for(let _d in data){
            if(data[_d]!== undefined){
                count++
            }
        };
        if(count>0){
            if(report){
                submit = Object.assign({},data,{
                    order_id:_this.state.cur,
                    template_id:0,
                    id:report.id
                });
                _this.props.dispatch(editReport(submit,function(res){
                    message.success('报告已保存')
                }))
            }else{
                submit = Object.assign({},data,{
                    order_id:_this.state.cur,
                    template_id:0
                });
                _this.props.dispatch(createReport(submit,function(res){
                    message.success('报告已保存！')
                }))
            }
        }else{}
    }
    componentWillMount(){
        this.props.form.setFieldsValue(this.props.orderData.report);
    }
    componentWillUnmount(){
        const token = this.props.user.accessToken;
        if(token){
            this.saveReport();
        }
    }
    componentWillReceiveProps(nextProp){
        if(nextProp.orderId != this.state.cur){
            this.saveReport();
            this.setState({
                cur:nextProp.orderId,
                orderData: nextProp.orderData
            },function(){
                this.props.form.resetFields();
                this.props.form.setFieldsValue(nextProp.orderData.report);
            })
        }
    }
    viewMP(e){
        e.preventDefault();
        const url = this.state.orderData.mp;
        window.open(
          url,
          'viewer',
          'location=no,toolbar=no,alwaysRaised=yes,screenX=0,screenY=0'
        );
    }
    render(){
        const patient=this.state.orderData.patient,
          study = this.state.orderData.study,
          pName = patient.name,
          pGender = patient.gender=="M"?'男':(patient.gender=="F"?'女':'未知'),
          pBirthday = patient.birthday,
          pAge= patient.age,
          { getFieldProps } = this.props.form,
          positiveProps = getFieldProps('positive', {
            rules: [
                { required: true,type:'number', message: '请选择诊断结果' }
            ]
        }),conformProps = getFieldProps('conform_diagnosis', {
            rules: [
                { required: true,type:'number', message: '请确认是否符合临床诊断' }
            ]
        }),criticalityProps = getFieldProps('criticality', {
            rules: [
                { required: true, message: '请选择危重值'}
            ]
        }),criticality = this.props.data.criticality && this.props.data.criticality.map(_h => {
            return (<Option key={_h.id} value={_h.name}>{_h.name}</Option>)
        }),findingsProps = getFieldProps('findings',{
            rules: [
                { required: true, message: '请填写检查所见内容'}
            ]
        }),impressionProps = getFieldProps('impression',{
            rules: [
                { required: true, message: '请填写影像学建议'}
            ]
        });
        return (
          <div>
              <div className="work-board">
                <h4>基本信息</h4>
                <ul className="label-list label-list-horizontal">
                    <li><label>姓名:</label>{pName}</li>
                    <li><label>性别:</label>{pGender}</li>
                    <li style={{width: '150px'}}><label>生日:</label>{pBirthday}</li>
                    <li><label>年龄:</label>{pAge}</li>
                </ul>
            </div>
            <div className="work-board">
                <h4>图片、影像基本信息</h4>
                <div>
                    <Button onClick={this.viewMP.bind(this)}>影像</Button>
                </div>
            </div>
              <Form horizontal form={this.props.form}>
                  <div className="work-board">
                      <h4>诊断</h4>
                      <FormItem
                        {...formItemLayout}
                        label="诊断结果"
                      >
                          <RadioGroup {...positiveProps}>
                              <RadioButton key={0} value={0}>阴性</RadioButton>
                              <RadioButton key={1} value={1}>阳性</RadioButton>
                          </RadioGroup>
                      </FormItem>
                      <FormItem
                        {...formItemLayout}
                        label="危重值"
                      >
                          <Select
                            {...criticalityProps}
                            showSearch
                            placeholder="请选择危重值"
                            optionFilterProp="children"
                            notFoundContent="无法找到"
                          >
                              {criticality}
                          </Select>
                      </FormItem>
                      <FormItem
                        {...formItemLayout}
                        label="符合临床诊断"
                      >
                          <RadioGroup {...conformProps}>
                              <RadioButton key={2} value={2}>符合</RadioButton>
                              <RadioButton key={1} value={1}>基本符合</RadioButton>
                              <RadioButton key={0} value={0}>不符合</RadioButton>
                          </RadioGroup>
                      </FormItem>

                      <FormItem>
                          <div className="work-board">
                              <h4>影像学表现</h4>
                          </div>
                          <Input
                            type="textarea"
                            placeholder="请选择模板"
                            autosize={{ minRows:8, maxRows: 12 }}
                            {...findingsProps}
                          />
                      </FormItem>
                      <FormItem>
                          <div className="work-board">
                              <h4>影像学建议</h4>
                          </div>
                          <Input
                            type="textarea"
                            placeholder="请选择模板"
                            autosize={{ minRows:8, maxRows: 12 }}
                            {...impressionProps}
                          />
                      </FormItem>
                      <FormItem>
                          <div className="work-board">
                              <Button onClick={this.endOrder.bind(this)} type="primary" size="large">提交报告</Button>&nbsp;
                              <Button onClick={this.saveReport.bind(this)}>暂存</Button>
                          </div>
                      </FormItem>
                  </div>
              </Form>
          </div>
        )
    }
}
WriteReport = Form.create()(WriteReport);
class OrderInfo extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            patient: this.props.order.patient,
            study: this.props.order.study,
            order:this.props.order.order,
            mp:this.props.order.mp
        }
    }
    viewMP(e){
        e.preventDefault();
        const url = e.target.dataset.mp;
        window.open(
          url,
          'viewer',
          'location=no,toolbar=no,alwaysRaised=yes,screenX=0,screenY=0'
        );
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            patient: nextProp.order.patient,
            study: nextProp.order.study,
            order:nextProp.order.order,
            mp:nextProp.order.mp
        })
    }
    render(){
        const patient = this.state.patient,
          study = this.state.study,
          order = this.state.order,
          mp = this.state.mp;
        return (
          <div className="card">
              <h3>当前患者信息</h3>
              <h4>患者基本信息</h4>
              <ul className="label-list label-list-short">
                  <li><label>姓名:</label>{patient.name || '--'}</li>
                  <li><label>性别:</label>{patient.gender == 'M'?'男':(patient.gender == 'F'?'女':'--')}</li>
                  <li><label>出生年月:</label>{patient.birthday || '--'}</li>
                  <li><label>年龄:</label>{study.patientage || '--'}</li>
                  <li><label>身份证号:</label>{patient.idcard || '--'}</li>
                  <li><label>过往病史:</label>{patient.medical_history || '--'}</li>
              </ul>
              <h4>影像信息</h4>
              <ul className="label-list label-list-short">
                  <li><label>来源:</label>自主上传</li>
                  <li><label>设备类型:</label>{study.modality || '--'}</li>
                  <li><label>检查部位:</label>{study.bodypart || '--'}</li>
                  <li><label>检查项目:</label>{study.check_item_name || '--'}</li>
                  <li><label>咨询费用:</label>{(order.price || '0')+'元'}</li>
                  <li><label>检查时间:</label>{study.studydate || '--'}</li>
                  <li><label>影像:</label>{mp?<a href="#" data-mp={mp} onClick={this.viewMP.bind(this)}>查看影像</a>:'暂无影像'}</li>
                  <li><label>检查号:</label>{study.accession_number || '--'}</li>
                  <li><label>症状描述:</label>{study.symptom || '--'}</li>
                  <li><label>临床诊断:</label>{study.diagnosis || '--'}</li>
              </ul>
          </div>
        )
    }
}

class Middle extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            currentWorking: this.props._cw,
            baseData: this.props.baseData
        };
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            currentWorking:nextProp._cw
        })
    }
    openWeiyi(){
        const _this = this,
          order = _this.state.currentWorking.order;
        _this.props.dispatch(openWeiyi(order.id,function(res){
            if(res.content.result === false){
                message.error(res.head.msg);
            }else{
                window.location = res.content
            }
        },function(res){
            message.error(res.head.msg,1)
        }))
    }
    onChangeTag(key){}
    render(){
        const _cw = this.state.currentWorking,
        order = _cw.order,
          user = _cw.user,
          baseData = this.state.baseData,
          orderCate = order.producttype,
          oid = order.id,
          consultant = {
              id:order.user_id,
              name:user.nickname || user.name || user.username || '佚名',
              eid:order.user_easemob_id
          },
          operations = (<Button onClick={this.openWeiyi.bind(this)} type="primary">开始会议</Button>),
          dispatch = this.props.dispatch;

        switch(orderCate){
            case "R":
            return (
              <Tabs >
                  <TabPane tab="写报告" key="r1">
                      <WriteReport
                        data={baseData}
                        orderId={oid}
                        orderData={_cw}
                        dispatch = {dispatch}
                        user={this.props.user}
                        orderChange={this.props.orderChange}
                      />
                  </TabPane>
              </Tabs>);
            case "V":
            return (
                <Tabs tabBarExtraContent={operations}>
                    <TabPane tab="写报告" key="v1">
                        <WriteReport
                          data={baseData}
                          orderId={oid}
                          orderData={_cw}
                          dispatch = {dispatch}
                          user={this.props.user}
                          orderChange={this.props.orderChange}
                        />
                    </TabPane>
                </Tabs>
            );
            case "G":
            return (
              <Tabs >
                  <TabPane tab="写报告" key="g1">
                      <WriteReport
                        data={baseData}
                        orderId={oid}
                        orderData={_cw}
                        dispatch = {dispatch}
                        user={this.props.user}
                        orderChange={this.props.orderChange}
                      />
                  </TabPane>
                  <TabPane tab="患者互动" ref="_t" key='g2'>
                      <ImEntry user={this.props.user} to={consultant} />
                  </TabPane>
              </Tabs>
            )
        }

    }
}
class _WorkBoard extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            defaultActiveKey:'1',
            currentWorking:{},
            baseData:{}
        };
        this.onChangeTag = this.onChangeTag.bind(this)
    }
    componentDidMount(){
        function _h_(){
            return {
                content:$(window).height()-80,
                sideList:$(window).height()-168
            }
        }
        setTimeout(function(){
            $('#contenter,.sideBar').height(_h_().content);
            $('.working-order').height(_h_().sideList)
        },0);
        $(window).resize(function(){
            $('#contenter,.sideBar').height(_h_().content);
            $('.working-order').height(_h_().sideList)
        });
        $('#boardTitle').hide();
    };
    componentWillMount(){
        let _order = {},
          _this = this;
        _this.props.dispatch(fetchOrderSpecial(1,'',function(res){
            _order.t1 = _.filter(res.content.list,(o)=>{
                return o.status >0 && o.status <3
            });
            _this.props.dispatch(fetchOrderSpecial(2,'',function(res){
                _order.t2 = _.filter(res.content.list,(o)=>{
                    return o.status >0 && o.status <3
                });
                _this.props.dispatch(fetchDatum([
                    {
                        name:'criticality',
                        enabled: true
                    }
                ],function(datas){
                    _this.setState({
                        order:{
                            t1:_order.t1,
                            t2:_order.t2
                        },
                        baseData:datas
                    },function(){
                        if(_this.state.order.t1.length>0){
                            _this.initialWorking('1',_this)
                        }else if(_this.state.order.t2.length>0){
                            _this.initialWorking('2',_this)
                        }
                    })
                }));
            }))
        }));

    };
    componentWillUnmount(){
        $('#boardTitle').show();
        $('#contenter').height('auto');
    }
    onChangeTag(key) {
        switch(key){
            case 'ol_2':
            function _h_(){
                return {
                    content:$(window).height()-80,
                    sideList:$(window).height()-168
                }
            }
            setTimeout(function(){
                $('#contenter,.sideBar').height(_h_().content);
                $('.working-order').height(_h_().sideList)
            },0);
            break;
        }
    }
    orderProcess(id,cb){
        this.props.dispatch(orderOperator(id,'process',function(res){
            message.info('开始处理订单...');
            if(typeof cb == 'function'){cb()}
        }))
    }
    working(e){
        e.preventDefault();
        const _this = this;
        const target = e.target.dataset.t,
          type = e.target.dataset.type,
          order = _.filter(_this.state.order['t'+type],d=>{
            return d.id == target
        })[0];
        _this.props.dispatch(fetchOrderRelatedData(order,function(d){
            const cw = {type:type,order:order,...d};
            _this.setState({
                currentWorking:cw
            },function(){
               try{$('.active').removeClass('active');
                _this.refs[target].className = 'order-item active';
                if(order.status<2){
                    _this.orderProcess(target,function(){
                        _this.orderChange(target,type,2)
                    })
                }
               }catch (e){console.info(e)}
            });
        }))
    }
    initialWorking(type,context){
        const order = context.state.order['t'+type][0];
        context.props.dispatch(fetchOrderRelatedData(order,function(d){
            context.setState({
                currentWorking:{type:type,order:order,...d}
            },function(){
                context.refs[order.id].className = 'order-item active';
                if(order.status<2){
                    context.orderProcess(order.id,function(){
                        context.orderChange(order.id,type,2)
                    })
                }
            });
        }))
    }
    renderOrderList(type){
        const _data = this.state.order[`t${type}`];
        if(!_data){
            return (<div style={{
                textAlign:'center',
                fontSize:'14px',
                color:'#999'
            }}>加载中...</div>)
        }else if(_data.length>0){
            let list = _.map(_data,(d,i)=>{
                return (
                  <li key={d.id} ref={d.id} className="order-item">
                      <a href="#" onClick={this.working.bind(this)} data-type={type} data-t={d.id}> </a>
                      <div>
                          <h5><b>{d.patientname}</b>的{d.check_item_name}</h5>
                          {type == 1?'':(<p>{d.productname}</p>)}
                          <p>{d.create_time}</p>
                          <i className={d.status == 1?'s1':(d.status == 2?'s2':'')}>{d.status == 1?'待处理':(d.status == 2?'处理中':'--')}</i>
                      </div>
                  </li>
                )
            });
            return (<ul style={{overflow:'auto'}} className="working-order">{list}</ul>)
        }else{
            return (<div style={{
                textAlign:'center',
                fontSize:'14px',
                color:'#999'
            }}>暂无需要处理的订单</div>)
        }
    }
    orderChange(id,type,status){
        const _this = this;
        let newOrder = _this.state.order;
        //let clone = Object.assign({},_this.state.order[`t${type}`]);
        let clone = _.clone(_this.state.order[`t${type}`]);
        switch (status){
            case 3:
                _.remove(clone,(o)=>{
                    return o.id == id
                })
                break;
            case 2:
            default:
                _.forEach(clone,(o)=>{
                    if(o.id == id){
                        o.status = status;
                    }
                });
        }
        newOrder[`t${type}`] = clone;
        if(status == 3){
            const other = type=='1'?'2':'1';
            if(newOrder[`t${type}`].length>0){
                _this.setState({
                    order:newOrder
                },function(){
                    _this.initialWorking(type,_this);
                })
            }else if(newOrder[`t${other}`].length>0){
                _this.setState({
                    order:newOrder
                },function(){
                    _this.initialWorking(other,_this);
                })
            }else{
                _this.setState({
                    order:newOrder,
                    currentWorking:{
                        type:null
                    }
                })
            }
        }else{
            _this.setState({
                order:newOrder
            })
        }
    }

    render(){
        const _type = this.state.currentWorking.type;
        if(_type){
            const order1= this.renderOrderList(1),
              order2= this.renderOrderList(2);
            return (
              <div id="workBoard">
                  {/*左侧区域*/}
                  <div className="sideBar leftBar" id="leftBar">
                      <div className="card">
                          <h3>待办事务</h3>
                          <Tabs defaultActiveKey={`ol_${_type}`} onChange={this.onChangeTag} size="small" >
                              <TabPane tab={`报告订单(${this.state.order.t1.length})`} key='ol_1'>
                                  {order1}
                              </TabPane>
                              <TabPane tab={`预约订单(${this.state.order.t2.length})`} key='ol_2'>
                                  {order2}
                              </TabPane>
                          </Tabs>
                      </div>
                  </div>
                  {/*中间区域*/}
                  <div style={{margin: '0 10px' }} id="mainBoard">
                      <Middle
                        dispatch={this.props.dispatch}
                        _cw={this.state.currentWorking}
                        baseData={this.state.baseData}
                        user={this.props.user}
                        orderChange={this.orderChange.bind(this)}
                      />
                  </div>
                  {/*右侧区域*/}
                  <div  className="sideBar rightBar" id="rightBar">
                      <OrderInfo order={this.state.currentWorking} />
                  </div>
              </div>
            )
        }else{
            return (<div style={{
                textAlign:'center',
                fontSize: '24px',
                color: '#999',
                padding: '30px 0',
                margin: '20px auto',
                width: '400px',
                backgroundColor: '#f5f5f5',
                borderRadius: '10px'
            }}>您暂时没有需要处理的订单...</div>)
        }
    }
}
let WorkBoard;
export default WorkBoard = connect((state) => {
    const {user} = state.rootReducer;
    return {user}
})(_WorkBoard)